package com.app.common.net.ly

import com.app.common.net.HttpProtocol

class LyApiResponseConverter : HttpProtocol.Converter<ApiLyService.Response> {

    companion object{

        @JvmStatic
        fun getCmd(source:String?):Int{
            return if (source.isNullOrEmpty()) {
                -1
            }else{
                source.sub("<Cmd>","</Cmd>").toIntOrNull()?:-1
            }
        }

        @JvmStatic
        fun getStatus(source:String?):Int{
            return if (source.isNullOrEmpty()) {
                -1
            }else{
                source.sub("<Status>","</Status>").toIntOrNull()?:-1
            }
        }
    }
    override fun onConvert(content: String?): ApiLyService.Response {
        return parse(content)
    }

    private fun parse(source:String?): ApiLyService.Response {
        if (source == null) {
            return ApiLyService.Response("",-1)
        }
/*        val fc = source.sub("<Function>", "</Function>")
        if (fc.isEmpty()) {
            return LyProtocol.Response("", -1)
        }*/
        if (!source.startsWith("<?xml")) {
            return ApiLyService.Response(source,-1)
        }
        val status = source.sub("<Status>","</Status>").toIntOrNull()
        var code = 0
        if (status !=null && status < 0) {
            code = status
        }
        val d = source.replace("> <",">\n<")
        //println("===="+Jsoup.parse(source).body().children())
        return ApiLyService.Response(d,code)
    }
}

fun String.sub(s: String,e:String):String{
    val sp = indexOf(s)
    if (sp == -1) {
        return ""
    }
    val ep = indexOf(e,sp)
    if (ep == -1) {
        return ""
    }

    return substring(sp+s.length,ep)
}